package com.life.ai.server.common.excel;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.life.ai.server.common.exception.ServiceException;
import com.life.ai.server.common.utils.ValidatorUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Map;
import java.util.Set;

/**
 * Excel 导入监听
 * DefaultReadListener
 *
 * @author kylewka
 * @since 2023/8/31
 */
@Slf4j
public class DefaultExcelListener<T> extends AnalysisEventListener<T>  implements ReadListener<T> {
    /**
     * 是否Validator检验，默认为是
     */
    protected Boolean isValidate = Boolean.TRUE;

    /**
     * 异常时不抛出
     */
    protected Boolean breakOnError = Boolean.TRUE;

    /**
     * excel 表头数据
     */
    protected Map<Integer, String> headMap;

    /**
     * 导入回执
     */
    protected final ExcelResult<T> excelResult;

    public DefaultExcelListener(boolean isValidate, boolean breakOnError) {
        this.excelResult = new ExcelResult<>();
        this.isValidate = isValidate;
        this.breakOnError = breakOnError;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        String errMsg = null;
        if (exception instanceof ExcelDataConvertException) {
            // 如果是某一个单元格的转换异常 能获取到具体行号
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            Integer rowIndex = excelDataConvertException.getRowIndex();
            Integer columnIndex = excelDataConvertException.getColumnIndex();
            errMsg = StrUtil.format("第{}行-第{}列-表头{}: 解析异常<br/>",
                    rowIndex + 1, columnIndex + 1, headMap.get(columnIndex));
            if (log.isDebugEnabled()) {
                log.error(errMsg);
            }
        }
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
            String constraintViolationsMsg = CollUtil.join(constraintViolations,", ", ConstraintViolation::getMessage);
            errMsg = StrUtil.format("第{}行数据校验异常: {}", context.readRowHolder().getRowIndex() + 1, constraintViolationsMsg);
            if (log.isDebugEnabled()) {
                log.error(errMsg);
            }
        }
        if (exception instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) exception;
            errMsg = StrUtil.format("第{}行: {}", context.readRowHolder().getRowIndex() + 1, serviceException.getMessage());
            if (log.isDebugEnabled()) {
                log.error(errMsg);
            }
        }
        excelResult.getErrorList().add(errMsg);
        if (breakOnError){
            throw new ValidationException(errMsg);
        }
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap = headMap;
        log.debug("解析到一条表头数据: {}", JSONUtil.toJsonStr(headMap));
    }

    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        if (isValidate) {
            ValidatorUtil.validate(data);
        }
        excelResult.getDataList().add(data);
        excelResult.increment(); // 成功数量计数+1
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.debug("所有数据解析完成！");
    }

    public ExcelResult<T> getExcelResult() {
        return excelResult;
    }
}
